const path = require("path");
const fs = require("fs");
let shell = require("shelljs");
const iconv = require("iconv-lite");

function parseConfig(dir, fileName) {
  let config = null;
  let dirArray = dir.split(path.sep);
  if (fs.existsSync(fileName)) {
    config = fileName;
  } else if (
    fs.existsSync(
      `.${path.sep}${dirArray[dirArray.length - 1]}${path.sep}${fileName}`
    )
  ) {
    config = `.${path.sep}${dirArray[dirArray.length - 1]}${
      path.sep
    }${fileName}`;
  } else if (fs.existsSync(`${dir}${path.sep}${fileName}`)) {
    config = `${dir}${path.sep}${fileName}`;
  }
  return config;
}

const $ = (cmd, options) => {
  let exec = shell.exec;
  let decode = (msg) => {
    return iconv.decode(iconv.encode(msg, "base64"), "gb2312");
  };
  return new Promise((resolve, reject) => {
    exec(
      cmd,
      { encoding: "base64", silent: true, ...options },
      (error, stdout, stderr) => {
        if (error) {
          reject(decode(stdout));
        } else {
          resolve(decode(stdout));
        }
      }
    );
  });
};

module.exports = { parseConfig, $ };
